package com.biz.primus.ms.promotion.service.promotion;

import com.biz.primus.base.enums.CommonStatus;
import com.biz.primus.base.exception.utils.AssertUtils;
import com.biz.primus.base.vo.PageVo;
import com.biz.primus.base.vo.promotion.PromotionProductVo;
import com.biz.primus.common.vo.SpringPageVO;
import com.biz.primus.model.promotion.exception.PromotionExceptionType;
import com.biz.primus.model.promotion.vo.UserFirstOrderCutPromotionVo;
import com.biz.primus.ms.base.service.AbstractBaseService;
import com.biz.primus.ms.promotion.dao.po.UserFirstOrderCutPromotion;
import com.biz.primus.ms.promotion.dao.repository.UserFirstOrderCutPromotionRepository;
import com.biz.primus.ms.promotion.service.feign.ProductFeignService;
import com.biz.primus.ms.promotion.trans.UserFirstOrderPromotionPo2VoMapper;
import com.google.common.collect.Lists;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户首单立减Service
 *
 * @author david-liu
 */
@Service
public class UserFirstOrderCutPromotionManagementServiceImpl extends AbstractBaseService implements UserFirstOrderCutPromotionManagementService {

    @Autowired
    private UserFirstOrderCutPromotionRepository userFirstOrderCutPromotionRepository;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUserFirstOrderCutPromotion(UserFirstOrderCutPromotionVo vo) {
        AssertUtils.notNull(vo, PromotionExceptionType.ILLEGAL_PARAMETER);
        UserFirstOrderCutPromotion userFirstOrderCutPromotion;
        if (Objects.isNull(vo.getId())) {
            userFirstOrderCutPromotion = new UserFirstOrderCutPromotion();
            userFirstOrderCutPromotion.setId(idService.getNextId());
        } else {
            userFirstOrderCutPromotion = userFirstOrderCutPromotionRepository.findOne(vo.getId());
        }
        userFirstOrderCutPromotion.setCutAmount(vo.getCutAmount());
        userFirstOrderCutPromotion.setProductAmountLimit(vo.getProductAmountLimit());
        userFirstOrderCutPromotion.setProductExcludeType(vo.getExcludeType());
        userFirstOrderCutPromotion.setExcludeProductIds(vo.getExcludeProductIds());
        userFirstOrderCutPromotion.setName(vo.getName());
        userFirstOrderCutPromotion.setDescription(vo.getDescription());
        userFirstOrderCutPromotion.setChannels(vo.getChannels());
        if (StringUtils.isNotBlank(vo.getStartTime())) {
            userFirstOrderCutPromotion.setStartTime(LocalDateTime.from(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").parse(vo.getStartTime())));
        }
        if (StringUtils.isNotBlank(vo.getEndTime())) {
            userFirstOrderCutPromotion.setEndTime(LocalDateTime.from(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").parse(vo.getEndTime())));
        }
        userFirstOrderCutPromotion.setEffectMemberLevels((Optional.ofNullable(vo.getEffectMemberLevels()).orElse(Lists.newArrayList()).stream().map(Integer::valueOf).collect(Collectors.toList())));
        userFirstOrderCutPromotion.setScope(vo.getScope());
        userFirstOrderCutPromotion.setScopeIds(Arrays.stream(StringUtils.split(vo.getScopeIds(), ",")).map(id -> Long.valueOf(StringUtils.trim(id))).collect(Collectors.toList()));
        userFirstOrderCutPromotion.setCommonStatus(vo.getCommonStatus());
        userFirstOrderCutPromotion.setAllowCoupon(vo.getAllowCoupon());;
        userFirstOrderCutPromotionRepository.save(userFirstOrderCutPromotion);
        return true;
    }

    @Override
    public SpringPageVO<UserFirstOrderCutPromotionVo> getUserFirstOrderCutPromotions(PageVo pageVo) {
        Page<UserFirstOrderCutPromotion> page = userFirstOrderCutPromotionRepository.findAll(pageVo.toPageRequest());
        if (!page.hasContent()) {
            return new SpringPageVO<>();
        }
        List<UserFirstOrderCutPromotion> userFirstOrderCutPromotions = page.getContent();
        Map<Long, List<PromotionProductVo>> excludeProducts = productFeignService.getUserFirstOrderPromotionExcludeProducts(userFirstOrderCutPromotions);
        List<UserFirstOrderCutPromotionVo> userFirstOrderCutPromotionVos = new UserFirstOrderPromotionPo2VoMapper().mapWithList(userFirstOrderCutPromotions, excludeProducts);
        return new SpringPageVO.Builder<UserFirstOrderCutPromotionVo>().size(page.getSize()).number(page.getNumber()).totalElements(page.getTotalElements()).content(userFirstOrderCutPromotionVos).build();
    }

    @Override
    public UserFirstOrderCutPromotionVo getUserFirstOrderCutPromotion(Long promotionId) {
        UserFirstOrderCutPromotion userFirstOrderCutPromotion = userFirstOrderCutPromotionRepository.findOne(promotionId);
        AssertUtils.notNull(userFirstOrderCutPromotion, PromotionExceptionType.ILLEGAL_STATE);
        List<PromotionProductVo> userFirstOrderExcludeProducts = productFeignService.getUserFirstOrderPromotionExcludeProducts(userFirstOrderCutPromotion);
        return new UserFirstOrderPromotionPo2VoMapper().map(userFirstOrderCutPromotion, userFirstOrderExcludeProducts);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean toggleUserFirstOrderCutPromotionStatus(Long promotionId) {
        UserFirstOrderCutPromotion userFirstOrderCutPromotion = userFirstOrderCutPromotionRepository.findOne(promotionId);
        AssertUtils.notNull(userFirstOrderCutPromotion, PromotionExceptionType.ILLEGAL_STATE);
        userFirstOrderCutPromotion.setCommonStatus(CommonStatus.toggle(userFirstOrderCutPromotion.getCommonStatus()));
        userFirstOrderCutPromotionRepository.save(userFirstOrderCutPromotion);
        return true;
    }
}
